package library.and.xps.com.step.util;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.jude.utils.JUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;

import io.realm.Realm;
import io.realm.RealmList;
import io.realm.RealmResults;
import library.and.xps.com.step.SPConstant;
import library.and.xps.com.step.m.model.Coordinate;
import library.and.xps.com.step.m.model.DaliyRecord;
import library.and.xps.com.step.m.model.RunRecord;
import library.and.xps.com.step.m.model.WeeklyRecord;

//用来插入更新查询步数
public class RunManager {
    private String TAG = this.getClass().getSimpleName();
    public static int STEP_NORECORD_YET = -1;
    private static final RunManager ourInstance = new RunManager();
    private Realm realm;

    public static RunManager getInstance() {
        return ourInstance;
    }

    private RunManager() {
        realm = Realm.getDefaultInstance();
    }

    /**
     * 更新运动记录
     * <p>
     *
     * @param bdLocation 百度定位信息
     */
    public void updateLog(final BDLocation bdLocation) {
        if (JUtils.getSharedPreference().getBoolean(SPConstant.APP_RUNNING, false)) {
            realm.beginTransaction();
            RealmResults<RunRecord> records = realm.where(RunRecord.class).findAll();
            RunRecord runRecord = records.get(records.size() - 1);

            RealmList<Coordinate> coordinates = runRecord.getmCoordinates();
            coordinates.add(inflatCoordinate(bdLocation));

            realm.insertOrUpdate(runRecord);

            realm.commitTransaction();
        }
    }

    Coordinate inflatCoordinate(BDLocation bdlocat) {
        LatLng latLng = new LatLng(bdlocat.getLatitude(), bdlocat.getLongitude());

        Coordinate coordinate = new Coordinate();
        coordinate.setSpeed(bdlocat.getSpeed());
        coordinate.setColorInSpeed(MapUtils.CulColorInSpeed(bdlocat.getSpeed()));
        coordinate.setAltitude(bdlocat.getAltitude());
        coordinate.setLat(latLng.latitude);
        coordinate.setLng(latLng.longitude);
        return coordinate;
    }

    /**
     * 标记运动开始
     * <p>
     */
    public void startRun() {

        long date = new Date().getTime();

        realm.beginTransaction();
        RunRecord d = new RunRecord();
        d.setStartTimeStamp(date);
        JUtils.getSharedPreference().edit().putLong(SPConstant.APP_RUN_START_TIME, date).commit();

        realm.insertOrUpdate(d);
        realm.commitTransaction();

        JUtils.getSharedPreference().edit().putBoolean(SPConstant.APP_RUNNING, true).commit();
    }

    /**
     * 标记运动结束
     * <p>
     */
    public void endRun() {
        realm.beginTransaction();
        RunRecord d = new RunRecord();
        d.setStartTimeStamp(JUtils.getSharedPreference().getLong(SPConstant.APP_RUN_START_TIME, 0));
        d.setCompleted(true);
        d.setEndTimeStamp(new Date().getTime());
        realm.insertOrUpdate(d);
        realm.commitTransaction();

        JUtils.getSharedPreference().edit().putBoolean(SPConstant.APP_RUNNING, false).commit();
        JUtils.getSharedPreference().edit().putLong(SPConstant.APP_RUN_START_TIME, 0).commit();
    }

    /**
     * 插入随机数据
     *
     * @param days 天数
     */
    public void insertRecord(int days) {
        ArrayList<DaliyRecord> daliyRecords = new ArrayList<>();

        Random r = new Random();
        for (int i = 0; i < days; i++) {
            DaliyRecord daliyRecord = new DaliyRecord();
            Date d = getAddDayDate(i);
            daliyRecord.setDate(d);
            daliyRecord.setTimeStamp(DateUtil.getDateMilliseconds(d));
            daliyRecord.setStepCount(r.nextInt(4000));
            daliyRecords.add(daliyRecord);
        }
        realm.beginTransaction();
        realm.insert(daliyRecords);
        realm.commitTransaction();
    }

    /**
     * 删除所有记录
     *
     * @return 操作是否成功
     */
    public boolean deleteAll() {
        boolean success;
        realm.beginTransaction();
        success = realm.where(RunRecord.class).findAll().deleteAllFromRealm();
        realm.commitTransaction();
        return success;
    }

    /**
     * 获取周视图的数据
     * 应该在总记录数量大于7时才能调用
     */
    public ArrayList<WeeklyRecord> getWeeklyRecord() {
        int i;
        int index = 0;
        ArrayList<WeeklyRecord> weekRecord = new ArrayList<>();
        ArrayList<DaliyRecord> allRecords = RToA(realm.where(DaliyRecord.class).findAll());
        int firstDayOfweek = DateUtil.getDayofWeek(allRecords.get(0).getTimeStamp());

        i = 8 - firstDayOfweek;
        WeeklyRecord weeklyRecord = new WeeklyRecord();

        if (i != 0) {
            ArrayList<DaliyRecord> eada = new ArrayList<>(allRecords.subList(0, i));
            weeklyRecord.setWeek(eada);
            index = i;
        }
        weekRecord.add(weeklyRecord);

        for (; ; i += 7) {
            if (i < allRecords.size()) {
                WeeklyRecord week = new WeeklyRecord();
                week.setWeek(new ArrayList<>(allRecords.subList(index, i)));
                weekRecord.add(week);
            } else {//边界情况 到这里i可能会大于allRecords的size
                WeeklyRecord week = new WeeklyRecord();
                week.setWeek(new ArrayList<>(allRecords.subList(index, allRecords.size())));
                weekRecord.add(week);
                break;
            }
            index = i;
        }

        Iterator<WeeklyRecord> iterator = weekRecord.iterator();
        while (iterator.hasNext()) {
            WeeklyRecord week = iterator.next();
            if (week.getWeek().size() <= 0)
                iterator.remove();
        }

        return weekRecord;
    }

    /*
    *  追加周视图数据至7天
    * */
    public ArrayList<WeeklyRecord> WeekRecordSupplement(ArrayList<WeeklyRecord> records) {
        ArrayList<WeeklyRecord> weeklyRecords = records;
        while (!(weeklyRecords.size() >= 7)) {
            WeeklyRecord weeklyRecord = new WeeklyRecord();
            weeklyRecords.add(weeklyRecord);
        }

        return weeklyRecords;
    }

    /**
     * return Latest DaliyRecord in db , otherwise return null
     *
     * @return DaliyRecord
     */
    public DaliyRecord getLatestRecord() {

        try {
            RealmResults<DaliyRecord> dailyrecord = realm.where(DaliyRecord.class).greaterThanOrEqualTo("date", DateUtil.getSuitDate()).findAll();
            if (dailyrecord != null && dailyrecord.size() != 0) {
                return dailyrecord.get(dailyrecord.size() - 1);
            }
        } catch (IllegalArgumentException ill) {
            ill.printStackTrace();
        }

        return null;
    }

    /**
     * 追加日视图数据到7天
     */
    public ArrayList<DaliyRecord> DayRecordSupplement(RealmResults<DaliyRecord> records) {
        int total = 7;

        ArrayList<DaliyRecord> records1 = RToA(records);

        while (records1.size() < total) {
            DaliyRecord daliyRecord = new DaliyRecord();
            Date d = getAddDayDate(total);
            daliyRecord.setDate(d);
            daliyRecord.setTimeStamp(DateUtil.getDateMilliseconds(d));
            daliyRecord.setStepCount(0);
            records1.add(daliyRecord);
        }

        return records1;
    }

    private Date getAddDayDate(int addDay) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, addDay);
        return calendar.getTime();
    }

    /**
     * 获取当天步数信息
     */
    public int getStepToday() {
        int step = STEP_NORECORD_YET;

        DaliyRecord record = getLatestRecord();
        if (record != null) {
            return record.getStepCount();
        }

        return step;
    }


    /**
     * RealmResult转换成Arraylist
     */
    public ArrayList<DaliyRecord> RToA(RealmResults<DaliyRecord> rrData) {
        ArrayList<DaliyRecord> re = new ArrayList<>();
        for (int i = 0; i < rrData.size(); i++) {
            re.add(rrData.get(i));
        }
        return re;
    }

}
